<?php

namespace App\Http\Middleware;

use App\Http\Util\HomeTool;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use GuzzleHttp\Client;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
class LockRedis
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $header = $request->header();
        if(!isset($header['signature'])){
            return response()->json(['error' => 'Invalid signtrue'], 401);
        }
        $signature = $header['signature'][0]; // 获取签名字段
        $timestamp = $header['timestamp'][0]; // 获取时间戳
//        unset($requestData['signature'], $requestData['timestamp']);

        $token = '98uu8ru8w0d9kc82ijr8uu8djek9id92'; // 从前端传递的密钥或令牌
        $requestData = $request->all();
        // 将请求参数和时间戳转换为字符串形式
        $stringToSign = $timestamp.$timestamp;
        // 使用密钥或令牌对请求参数和时间戳进行签名
        $generatedSignature = hash_hmac( 'sha512', utf8_encode($stringToSign), utf8_encode($token));

//        $time = time();
//        if($time-$timestamp > 15){
//             return response()->json(['error' => 'Invalid timestamp'], 403);
//        }

        // 验证签名是否一致
        if ($generatedSignature !== $signature) {
            // 验证失败，返回错误响应
            return response()->json(['error' => 'Invalid signtrue'], 401);
        }
        return $next($request);
    }
}
